package com.lzc.springPart;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigUtils;

import java.util.Comparator;
import java.util.function.Supplier;

/**
 * beanFactory的实现
 */
public class BeanFactoryImpl {

    public static void main(String[] args) {

        // 空的容器
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        // 添加bean的定义 beanDefinition 让容器根据bean的定义创建bean
        // 描述bean (class, scope, 初始化, 销毁, 等等描述信息)

        // 创建beanDefinition
        AbstractBeanDefinition configDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class)
                .setScope("singleton")
                .getBeanDefinition();

        // 注册beanDefinition
        beanFactory.registerBeanDefinition("config",configDefinition);


        // 打印beanDefinition
        for (String name : beanFactory.getBeanDefinitionNames()) {
            System.out.println(name);
        }

        // 添加beanFactoryPostProcess
        AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory);

        System.out.println("-----------------添加beanFactory后处理器---------------------------");

        // 打印beanDefinition
        for (String name : beanFactory.getBeanDefinitionNames()) {
            System.out.println(name);
        }

        // getBeansOfType 方法执行会生成对应的bean
        beanFactory.getBeansOfType(BeanFactoryPostProcessor.class)
                .entrySet()
                .stream().forEach(e ->{
                    e.getValue().postProcessBeanFactory(beanFactory);
                });

        System.out.println("-----------------执行beanFactory后处理器-------------------------");

        // 打印beanDefinition
        // beanFactory后处理器作用是添加beanDefinition信息
        for (String name : beanFactory.getBeanDefinitionNames()) {
            System.out.println(name);
        }

        // bean后处理器, 针对bean的生命周期各个阶段提供扩展
        // 创建对应的bean 并且加入beanFactory容器的 beanPostProcessor集合，在bean创建的各个生命周期会调用
        // 按加入list集合的顺序执行
        beanFactory.getBeansOfType(BeanPostProcessor.class).values()
                        .forEach(beanFactory::addBeanPostProcessor);


        // 提前创建单例bena
        beanFactory.preInstantiateSingletons();


    }
}
